<?php

declare(strict_types=1);

namespace App\CustHub\Controller;

use App\Common\Service\Affiliate\AffiliateFactory;
use App\CustHub\Annotation\ApiAuth;
use App\CustHub\Annotation\VerifySignature;
use App\CustHub\Constants\AffiliateAccountTypeConstants;
use App\CustHub\Request\AffiliateAccountRequest;
use App\CustHub\Service\AffiliateAccountService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;
use Psr\Http\Message\ResponseInterface;

#[Controller(prefix: "ch/affiliate/account"),ApiAuth,VerifySignature]
class AffiliateAccountController extends BaseController
{
    #[Inject]
    protected AffiliateAccountService $service;

    #[Inject]
    protected AffiliateFactory $affiliateFactory;

    #[PostMapping('list')]
    public function list()
    {
        $data = $this->request->all();
        return $this->success($this->service->getAccountList($data));
    }


    /**
     * 获取联盟授权地址
     * @param AffiliateAccountRequest $request
     * @return ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('getOauthUrl')]
    public function getOauthUrl(AffiliateAccountRequest $request): ResponseInterface
    {
        $data = $request->all();
        $code = AffiliateAccountTypeConstants::getCode((int)$data['type']);
        if(empty($code)){
            return $this->error('参数错误');
        }

        $oauthUrl = $this->affiliateFactory->getService($code)->getAuthUrl($data);
        return $this->success(['url' => $oauthUrl]);
    }

    /**
     * 保存无需授权的联盟账号信息
     * @param AffiliateAccountRequest $request
     * @return ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('save')]
    public function save(AffiliateAccountRequest $request): ResponseInterface
    {
        return $this->service->save($request->all()) ? $this->success() : $this->error();
    }

    #[PostMapping('delete')]
    public function delete(AffiliateAccountRequest $request): ResponseInterface
    {
        return $this->service->deleteAccount($request->all()) ? $this->success() : $this->error();
    }
}